package top.zhongyy.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import top.zhongyy.enumPackage.TouristEnum;
import top.zhongyy.pojo.BlogLog;
import top.zhongyy.mapper.BlogLogMapper;
import top.zhongyy.service.BlogLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.zhongyy.util.IPUtils;
import top.zhongyy.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Andy
 * @since 2021-04-06
 */
@Service
public class BlogLogServiceImpl extends ServiceImpl<BlogLogMapper, BlogLog> implements BlogLogService {
    
    @Autowired
    private BlogLogService blogLogService;
    
    
    @Override
    public void addLog(String logUrl, String logClassMethod, HttpServletRequest request) throws IOException {
        String IPV4 = IPUtils.getIpAddr(request);
        BlogLog blogLog = new BlogLog();
        int fourDot = StringUtils.ordinalIndexOf(logClassMethod, ".", 4);
        int threeDot = StringUtils.ordinalIndexOf(logClassMethod, ".", 3);
        blogLog.setLogUrl(logUrl);
        blogLog.setLogClassMethod(logClassMethod);
        blogLog.setLogInfo(TouristEnum.valueOf(StringUtil.toUnderlineUpperCase(logClassMethod.substring(fourDot + 1))).getDesc());
        blogLog.setLogModule(TouristEnum.valueOf(StringUtil.toUnderlineUpperCase(logClassMethod.substring(threeDot + 1, fourDot)).substring(1)).getDesc());
        blogLog.setLogIp(IPV4);
        blogLog.setBrowser(IPUtils.getBrowser(request));
        blogLog.setClientOS(IPUtils.getClientOS(request));
        
        try {
            if (IPV4.equals("0:0:0:0:0:0:0:1")) {
                blogLog.setLogAddress("局域网");
            } else {
                blogLog.setLogAddress(IPUtils.getAddress(blogLog.getLogIp()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        try {
            if (IPV4.equals("0:0:0:0:0:0:0:1")) {
                blogLog.setLogOperator("对方和您在同一内部网");
            } else {
                blogLog.setLogOperator(IPUtils.getOperator(blogLog.getLogIp()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        blogLogService.save(blogLog);
    }
    
}
